"""
知识库和文档模型
"""

from sqlalchemy import Column, Integer, String, DateTime, Text, Boolean, JSON, ForeignKey
from sqlalchemy.sql import func
from sqlalchemy.orm import relationship
from app.database import Base


class KnowledgeBase(Base):
    """知识库表"""
    
    __tablename__ = "knowledge_bases"
    
    id = Column(Integer, primary_key=True, index=True, comment="知识库ID")
    name = Column(String(100), nullable=False, comment="知识库名称")
    description = Column(Text, comment="知识库描述")
    collection_name = Column(String(100), unique=True, nullable=False, comment="Chroma集合名称")
    embedding_model = Column(String(100), default="text-embedding-ada-002", comment="嵌入模型")
    chunk_size = Column(Integer, default=1000, comment="文档分块大小")
    chunk_overlap = Column(Integer, default=200, comment="分块重叠大小")
    is_active = Column(Boolean, default=True, comment="是否激活")
    document_count = Column(Integer, default=0, comment="文档数量")
    total_chunks = Column(Integer, default=0, comment="总块数")
    created_at = Column(DateTime(timezone=True), server_default=func.now(), comment="创建时间")
    updated_at = Column(DateTime(timezone=True), server_default=func.now(), onupdate=func.now(), comment="更新时间")
    
    # 关系
    documents = relationship("Document", back_populates="knowledge_base", cascade="all, delete-orphan")
    
    def __repr__(self):
        return f"<KnowledgeBase(id={self.id}, name='{self.name}')>"


class Document(Base):
    """文档表"""
    
    __tablename__ = "documents"
    
    id = Column(Integer, primary_key=True, index=True, comment="文档ID")
    knowledge_base_id = Column(Integer, ForeignKey("knowledge_bases.id"), nullable=False, comment="知识库ID")
    filename = Column(String(255), nullable=False, comment="文件名")
    original_filename = Column(String(255), nullable=False, comment="原始文件名")
    file_path = Column(String(500), nullable=False, comment="文件路径")
    file_size = Column(Integer, comment="文件大小（字节）")
    file_type = Column(String(50), comment="文件类型")
    content = Column(Text, comment="文档内容")
    document_metadata = Column(JSON, default={}, comment="文档元数据")
    chunk_count = Column(Integer, default=0, comment="分块数量")
    is_processed = Column(Boolean, default=False, comment="是否已处理")
    processing_status = Column(String(50), default="pending", comment="处理状态")
    error_message = Column(Text, comment="错误信息")
    created_at = Column(DateTime(timezone=True), server_default=func.now(), comment="创建时间")
    updated_at = Column(DateTime(timezone=True), server_default=func.now(), onupdate=func.now(), comment="更新时间")
    
    # 关系
    knowledge_base = relationship("KnowledgeBase", back_populates="documents")
    
    def __repr__(self):
        return f"<Document(id={self.id}, filename='{self.filename}', knowledge_base_id={self.knowledge_base_id})>"
